package tom.vertx.core.demo05;

import io.vertx.core.Vertx;
import io.vertx.core.net.JksOptions;
import io.vertx.core.net.KeyCertOptions;
import io.vertx.core.net.SelfSignedCertificate;
import io.vertx.core.net.TrustOptions;
import lombok.extern.slf4j.Slf4j;

/**
 * 证书生成:  https://blog.csdn.net/fly_leopard/article/details/78810834
 * @author ZHUFEIFEI
 */
@Slf4j
public class TcpDemo {

  /**
   * ssl自签名, 用于开发 测试
   */
  static SelfSignedCertificate certificate = SelfSignedCertificate.create();

  public static void main(String[] args) {
    Vertx vertx = Vertx.vertx();
    //一个启用一个不启用, 默认client可以连接server, 但是server将不处理client请求, 通过server端配置setClientAuth设置是否要求客户端使用ssl,默认NONE
    //设置为require , 客户端连接直接失败
    vertx.deployVerticle(new MyTcpServer(true), res -> {
      if (res.succeeded()) {
        log.info("Tcp Server running.");
        vertx.deployVerticle(new MyTcpClient(true), complete -> {
          if (complete.succeeded()) {
            log.info("Tcp Client running.");
          } else {
            complete.cause().printStackTrace();
          }
        });
      } else {
        log.warn("Tcp Server run failed.");
      }
    });
  }

  public static KeyCertOptions keyCertOptions() {
    String invoker = Thread.currentThread().getStackTrace()[2].getClassName();
    log.info("KeyCertOptions => {} {}", invoker, MyTcpServer.class.getName().equals(invoker));
    //jks证书 keystore truststore一体, 双向认证的,client server都使用server-keystore.jks即可
    return new JksOptions().setPath("server-keystore.jks").setPassword("serverpwd");
//    return certificate.keyCertOptions();
  }

  public static TrustOptions trustOptions() {
    String invoker = Thread.currentThread().getStackTrace()[2].getClassName();
    log.info("TrustOptions => {} {}", invoker, MyTcpServer.class.getName().equals(invoker));
    //jks证书 keystore truststore一体
    return new JksOptions().setPath("server-keystore.jks").setPassword("serverpwd");
//    return certificate.trustOptions();
  }

}
